package com.wb.spring.boot.autoconfigure.http;

import com.wb.spring.boot.autoconfigure.WbProperties;
import com.wb.spring.boot.autoconfigure.WbRpcAutoConfiguration;
import com.wb.spring.boot.autoconfigure.proxy.WbClientCall;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.AsyncRestTemplate;
import org.springframework.web.client.RestTemplate;


/**
 * @Author deeprado
 * @Date 2022/8/25 19:25
 */

@Slf4j
@Configuration
@AutoConfigureAfter({WbRpcAutoConfiguration.class, WbOkHttpAutoConfiguration.class, WbHttpClientAutoConfiguration.class, WbDefaultHttpAutoConfiguration.class})
public class WbAsyncClientAutoConfiguration {

    @Bean
    @ConditionalOnBean(RestTemplate.class)
    @ConditionalOnMissingBean
//    @ConditionalOnAsyncClientEnabled
    public AsyncRestTemplate asyncRestTemplate(RestTemplate restTemplate) {
        log.info(" asyncRestTemplate = {}", restTemplate);
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        SimpleAsyncTaskExecutor asyncTaskExecutor = new SimpleAsyncTaskExecutor();
        asyncTaskExecutor.setConcurrencyLimit(10);
        requestFactory.setTaskExecutor(asyncTaskExecutor);
        return new AsyncRestTemplate(requestFactory, restTemplate);
    }

    @Bean
    @ConditionalOnBean(RestTemplate.class)
    @ConditionalOnMissingBean
    public WbClientCall clientCall(WbProperties wbProperties) {
        return new WbClientCall(wbProperties.isAsync(), wbProperties.getMaxAttempts());
    }

}
